package com.gaff.emp.core.mybatis;

import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.gaff.emp.core.modules.auth.LoginUserInfo;
import com.gaff.emp.core.mybatis.annotation.CreatedDate;
import com.gaff.emp.core.mybatis.annotation.CreatedBy;
import com.gaff.emp.core.mybatis.annotation.ModifiedBy;
import com.gaff.emp.core.mybatis.annotation.ModifiedDate;
import com.gaff.emp.core.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.Properties;

@Slf4j
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class AuditInterceptor extends AbstractSqlParserHandler implements Interceptor {

    private Properties properties;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (parameter == null) {
            return invocation.proceed();
        }
        Field[] fields = parameter.getClass().getDeclaredFields();
        if (SqlCommandType.UPDATE == sqlCommandType && mappedStatement.getId().contains("updateById")) {
            parameter = ((MapperMethod.ParamMap) parameter).get("et");
            fields = parameter.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (AnnotationUtils.getAnnotation(field, ModifiedBy.class) != null) {
                    setAuditUsername(field, parameter);
                    continue;
                }
                if (AnnotationUtils.getAnnotation(field, ModifiedDate.class) != null) {
                    setAuditDate(field, parameter);
                    continue;
                }
            }
        } else if (SqlCommandType.INSERT == sqlCommandType) {
            for (Field field : fields) {
                if (AnnotationUtils.getAnnotation(field, ModifiedBy.class) != null || AnnotationUtils.getAnnotation(field, CreatedBy.class) != null) {
                    setAuditUsername(field, parameter);
                    continue;
                }
                if (AnnotationUtils.getAnnotation(field, ModifiedDate.class) != null || AnnotationUtils.getAnnotation(field, CreatedDate.class) != null) {
                    setAuditDate(field, parameter);
                    continue;
                }
            }
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        }
        return target;
    }

    @Override
    public void setProperties(Properties prop) {
        this.properties = prop;
    }

    private void setAuditUsername(Field field, Object parameter) throws IllegalAccessException {
        field.setAccessible(true);
        LoginUserInfo currentUser = ContextUtil.getCurrentUserInfo();
        if (currentUser != null) {
            field.set(parameter, currentUser.getUser().getUsername());
        } else {
            field.set(parameter, "unknown");
        }
        field.setAccessible(false);
    }

    private void setAuditDate(Field field, Object parameter) throws IllegalAccessException {
        field.setAccessible(true);
        field.set(parameter, new Date());
        field.setAccessible(false);
    }

}
